<template>
  <div class="back-to-top" @click="backTop" v-show="show">
    回到<br>
    顶部
  </div>
</template>

<script>
  export default {
    name:'back-to-top',
    props: {
      time: {
        type: Number,
        default: 1000
      }
    },
    data(){
      return {
         iswheel: false,
         show: false
      }
    },
    methods:{
      // 回到顶部
      backTop(){
        let topValue = document.body.scrollTop || document.documentElement.scrollTop;
        let that = this;
        this.iswheel = false;
        backZero();

        function backZero(){//自己模拟匀速动画
          if(that.iswheel){
            return;
          }
          topValue -= that.time/16.7;
          if(topValue<=0){
            document.body.scrollTop = document.documentElement.scrollTop = 0;
            return;
          }
         document.body.scrollTop = document.documentElement.scrollTop = topValue;
         requestAnimationFrame(backZero)
        }
      },
      //判断当前位置显示和隐藏按钮
      isExist(){
        let topValue = document.body.scrollTop || document.documentElement.scrollTop;
        if(topValue > 100){
          this.show = true;
        }else{
          this.show = false;
        }
      }
    },
    mounted(){
      this.isExist();
      document.addEventListener('wheel',()=>{
        this.iswheel = true;
      })
      document.addEventListener('scroll',()=>{
        this.isExist();
      })
    }
  }
</script>

<style lang="scss">
  .back-to-top{
    width: 45px;
    height: 45px;
    border-radius: 50%;
    position: fixed;
    bottom: 50px;
    right: 50px;
    font-size: 12px;
    @include flex;
    background-color: eee;
    border: 1px solid #ddd;
    box-shadow: $box-shadow-bottom;
    cursor: pointer;
    z-index: 99;
  }
</style>
